package com.feature.core.util;

import java.util.Map;

import javax.crypto.SecretKey;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;

/**
 * Jwt工具类
 *
 */
public class JwtUtils {
    private static final byte[] secret = new byte[] { 46, -75, -41, 45, -4, -86, 51, 48, -117, 61, -101, -16, 86, 102, -45, -112, -4, 34, 54, 63, -24, -41, -67, -118, -33, 10, 60, -35, -80, 58, 82,
            -23, -95, 56, 108, -10, -69, -24, -67, -46, 5, -101, 89, -54, 35, -76, -11, 59, 64, -61, 2, 1, 24, 44, 2, 84, 52, 72, -127, -22, 41, -28, -14, 36 };

    private static final SecretKey secretKey = Keys.hmacShaKeyFor(secret);

    /**
     * 从数据声明生成令牌
     *
     * @param claims 数据声明
     * @return 令牌
     */
    public static String createToken(Map<String, Object> claims) {
        String token = Jwts.builder().claims(claims).signWith(secretKey, Jwts.SIG.HS512).compact();
        return token;
    }

    /**
     * 从令牌中获取数据声明
     *
     * @param token 令牌
     * @return 数据声明
     */
    public static Claims parseToken(String token) {
        return Jwts.parser().verifyWith(secretKey).build().parseSignedClaims(token).getPayload();
    }

    /**
     * 根据令牌获取用户ID
     * 
     * @param token 令牌
     * @return 用户ID
     */
    @SuppressWarnings("unchecked")
    public static <T> T getValue(String token, String key) {
        Claims claims = parseToken(token);
        return (T) claims.get(key);
    }
}
